import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/view/calendar_view.dart';
import 'package:excel_utils/pages/week/bean/QuotationRecordBean.dart';
import 'package:excel_utils/pages/week/week_entry/child/quotation_record/bloc/quotation_record_cubit.dart';
import 'package:excel_utils/repository/week/quotation_record_repository.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class QuotationRecordPage extends StatefulWidget {
  const QuotationRecordPage({super.key});

  @override
  State<QuotationRecordPage> createState() => _QuotationRecordPageState();
}

class _QuotationRecordPageState extends State<QuotationRecordPage> {

  late String startDateStr;
  late String endDateStr;

  QuotationRecordCubit? quotationRecordCubit;
  List<QuotationRecordBean> quotationRecordList = [];
  bool searchLoading = false;
  Set<String> deleteIdData = {};
  bool saveLoading = false;

  @override
  Widget build(BuildContext context) {
    return BlocProvider<QuotationRecordCubit>(
      create: (context) => QuotationRecordCubit(context.read<QuotationRecordRepository>()),
      child: BlocConsumer<QuotationRecordCubit, QuotationRecordState>(
        builder: (BuildContext context, QuotationRecordState state) {
          quotationRecordCubit = quotationRecordCubit ?? context.read<QuotationRecordCubit>();
          if (state is QuotationRecordDataLoading) {
            searchLoading = true;
          } else if (state is QuotationRecordDataSuccessState) {
            searchLoading = false;
            quotationRecordList = state.quotationRecordData;
            if (quotationRecordList.isEmpty) {
              quotationRecordList.add(QuotationRecordBean.empty());
            }
          } else if (state is QuotationRecordDataFailureState) {
            searchLoading = false;
          } else if (state is QuotationRecordDeleteLoading) {
            deleteIdData.add(state.quotationRecordId);
          } else if (state is QuotationRecordSaveLoading) {
            saveLoading = true;
          } else if (state is QuotationRecordSaveSuccessState) {
            saveLoading = false;
            quotationRecordList = state.quotationRecordData;
          } else if (state is QuotationRecordDeleteSuccessState) {
            deleteIdData.remove(state.quotationRecordId);
            quotationRecordList.removeWhere((element) => element.id.toString() == state.quotationRecordId);
          } else if (state is QuotationRecordDeleteFailureState) {
            deleteIdData.remove(state.quotationRecordId);
          }
          return buildUI();
        },
        listener: (BuildContext context, state) {
          if (state is QuotationRecordSaveSuccessState) {
            String message = "保存成功";
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
          }
        },
      ),
    );
  }

  Widget buildUI() {
    return Container(
      padding: EdgeInsets.all(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("客服报价记录", style: TextStyle(fontSize: 20, color: Colors.blue, fontWeight: FontWeight.bold)),
          Text("选择时间范围"),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CalendarView(
                onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                  startDateStr = "${startStr}";
                  endDateStr = "${endStr}";
                },
                onDateStartChanged: (startDateTime, startStr) {
                  print("disMonthFeeStartDate: $startDateTime, $startStr");
                  startDateStr = "${startStr}";
                },
                onDateEndChanged: (endDateTime, endStr) {
                  print("disMonthFeeEndDate: $endDateTime, $endStr");
                  endDateStr = "${endStr}";
                },
              ),
              if (searchLoading)
                Center(child: CircularProgressIndicator())
              else
                TextButton(
                    onPressed: () {
                      quotationRecordCubit?.getQuotationRecord(maps: {"startDate": "$startDateStr", "endDate": "$endDateStr"});
                    },
                    child: Text("获取数据")),
            ],
          ),
          const Row(
            children: [
              Expanded(child: Center(child: Text("No."))),
              Expanded(child: Center(child: Text("報價日期"))),
              Expanded(child: Center(child: Text("負責客服"))),
              Expanded(child: Center(child: Text("客戶公司名稱"))),
              Expanded(child: Center(child: Text("客戶地區"))),
              Expanded(child: Center(child: Text("聯絡人"))),
              Expanded(child: Center(child: Text("電話"))),
              Expanded(child: Center(child: Text("如何得知本公司途徑"))),
              Expanded(child: Center(child: Text("想開月費 / 套票"))),
              Expanded(child: Center(child: Text("報了什麼價  (工商/偏遠/標準/優惠價)"))),
              Expanded(child: Center(child: Text("後續跟進結果(半天後詢問客戶, 也可將客戶反映意見告知)"))),
              Expanded(child: Center(child: Text("是否成功開戶"))),
              Expanded(child: Center(child: Text("数据归属日期范围"))),
              Expanded(child: Center(child: Text("操作"))),
            ],
          ),
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: quotationRecordList.length,
            itemBuilder: (BuildContext context, int index) {
              QuotationRecordBean quotationRecord = quotationRecordList[index];
              return Row(
                children: [
                  Expanded(child: Center(child: Text("${index + 1}"))),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.quotationDate),
                          onChanged: (value) => quotationRecordList[index].quotationDate = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.personCharge),
                          onChanged: (value) => quotationRecordList[index].personCharge = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.customerCompanyName),
                          onChanged: (value) => quotationRecordList[index].customerCompanyName = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.customerRegion),
                          onChanged: (value) => quotationRecordList[index].customerRegion = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.contactPerson),
                          onChanged: (value) => quotationRecordList[index].contactPerson = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.phone),
                          onChanged: (value) => quotationRecordList[index].phone = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.source),
                          onChanged: (value) => quotationRecordList[index].source = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.monthlyOrPackage),
                          onChanged: (value) => quotationRecordList[index].monthlyOrPackage = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.quotation),
                          onChanged: (value) => quotationRecordList[index].quotation = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.followUp),
                          onChanged: (value) => quotationRecordList[index].followUp = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.result),
                          onChanged: (value) => quotationRecordList[index].result = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: TextField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                          ),
                          controller: TextEditingController(text: quotationRecord.dateRange),
                          onChanged: (value) => quotationRecordList[index].dateRange = value)),
                  SizedBox(width: 3),
                  Expanded(
                      child: deleteIdData.contains(quotationRecord.id.toString())
                          ? Center(
                              child: CircularProgressIndicator(),
                            )
                          : TextButton(
                              onPressed: () {
                                if (quotationRecord.id == null) {
                                  quotationRecordList.removeAt(index);
                                  setState(() {});
                                } else {
                                  quotationRecordCubit?.deleteQuotationRecord(quotationRecordId: quotationRecord.id.toString());
                                }
                              },
                              child: Text("Del"),
                            )),
                  SizedBox(width: 3),
                ],
              );
            },
          ),
          Row(
            children: [
              Flexible(
                  child: TextButton(
                      onPressed: () {
                        StringBuffer sb = StringBuffer();
                        for (var i = 0; i < quotationRecordList.length; i++) {
                          QuotationRecordBean quotationRecord = quotationRecordList[i];
                          sb.writeln(
                              "${i+1}\t${quotationRecord.quotationDate}\t${quotationRecord.personCharge}\t${quotationRecord.customerCompanyName}\t${quotationRecord.customerRegion}\t${quotationRecord.contactPerson}\t${quotationRecord.phone}\t${quotationRecord.source}\t${quotationRecord.monthlyOrPackage}\t${quotationRecord.quotation}\t${quotationRecord.followUp}\t${quotationRecord.result}");
                        }
                        sb.toString().replaceAll("\r", "").copyValue();
                      },
                      child: Text("COPY"))),

              // 添加一条记录
              Flexible(
                child: TextButton(
                    onPressed: () {
                      DateTime now = DateTime.now();
                      now.month.toString().padLeft(2, '0');
                      String createDate = "${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}";
                      quotationRecordList.add(QuotationRecordBean(
                          quotationDate: "",
                          personCharge: "",
                          customerCompanyName: "",
                          customerRegion: "",
                          contactPerson: "",
                          phone: "",
                          source: "",
                          monthlyOrPackage: "",
                          quotation: "",
                          followUp: "",
                          result: "成功",
                          dateRange: "",
                          createDate: "${createDate}"));
                      setState(() {});
                    },
                    child: Text("添加")),
              ),

              if (saveLoading)
                CircularProgressIndicator()
              else
                Flexible(
                  child: TextButton(
                      onPressed: () {
                        bool isNotEmpty = false;
                        for (var quotationRecord in quotationRecordList) {
                          if (quotationRecord.quotationDate == "") {
                            isNotEmpty = true;
                            break;
                          }
                          if (quotationRecord.personCharge == "") quotationRecord.personCharge = " ";
                          if (quotationRecord.customerCompanyName == "") quotationRecord.customerCompanyName = " ";
                          if (quotationRecord.customerRegion == "") quotationRecord.customerRegion = " ";
                          if (quotationRecord.contactPerson == "") quotationRecord.contactPerson = " ";
                          if (quotationRecord.phone == "") quotationRecord.phone = " ";
                          if (quotationRecord.monthlyOrPackage == "") quotationRecord.monthlyOrPackage = " ";
                          if (quotationRecord.quotation == "") quotationRecord.quotation = " ";
                          if (quotationRecord.followUp == "") quotationRecord.followUp = " ";
                          if (quotationRecord.dateRange == "") {
                            isNotEmpty = true;
                            break;
                          }
                        }

                        if (isNotEmpty) {
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("请填写完整数据")));
                          return;
                        }
                        quotationRecordCubit?.saveQuotationRecord(quotationRecord: quotationRecordList);
                      },
                      child: Text("保存")),
                ),
            ],
          ),
          SizedBox(
            height: 50,
          )
        ],
      ),
    );
  }

  Widget calendarDatePicker(
      {year,
      month,
      day,
      bool row = false,
      DateTime? currentStartDate,
      DateTime? currentEndDate,
      required Function(String, DateTime) startOnDateChanged,
      required Function(String, DateTime) endOnDateChanged}) {
    Widget startWidget = SizedBox(
      width: 280,
      height: 200,
      child: CalendarDatePicker(
          initialDate: null,
          currentDate: currentStartDate ?? DateTime(year, month, day - 1, 00, 00, 00),
          firstDate: DateTime(2024, 1, 1, 0, 0, 0),
          lastDate: DateTime(2030, 1, 1, 23, 59, 59),
          onDateChanged: (date) {
            var startTime = "${date.year}-${date.month < 9 ? "0${date.month}" : date.month}-${date.day < 9 ? "0${date.day}" : date.day} 00:00:00";
            startOnDateChanged(startTime, date);
          }),
    );
    Widget endWidget = SizedBox(
      width: 280,
      height: 200,
      child: CalendarDatePicker(
          initialDate: null,
          currentDate: currentEndDate ?? DateTime(year, month, day - 1, 59, 59, 59),
          firstDate: DateTime(2024, 1, 1, 0, 0, 0),
          lastDate: DateTime(2030, 1, 1, 23, 59, 59),
          onDateChanged: (date) {
            var endTime = "${date.year}-${date.month < 9 ? "0${date.month}" : date.month}-${date.day < 9 ? "0${date.day}" : date.day} 23:59:59";
            endOnDateChanged(endTime, date);
          }),
    );
    if (row) {
      return Row(children: [startWidget, endWidget]);
    } else {
      return Column(children: [startWidget, endWidget]);
    }
  }
}
